﻿#region Using directives

using System;
using System.Text;
using System.CodeDom;
using System.Collections.Generic;

using Weazel.Math;
using Weazel.Gezel.Model;

#endregion

namespace Weazel.Gezel.Conversions.Model
{
  public class RegisterType : SignalTypeBase
  {
    private Register register;
    private IntegerField storedValueField;

    private Method tickMethod;

    public RegisterType(Register register, ControllerType controllerType, SoftwareModel softwareModel) : base(
      String.Format("Register_{0}", register.Name.Replace(".", "_")), 
      register,
      controllerType, 
      softwareModel, 
      register.Width, 
      register.Signed)
    {
      this.register = register;
			this.BaseTypes.Add(new CodeTypeReference("IRegister"));

      storedValueField = AddIntegerField("StoredValue", register.Width, register.Signed, "0");
      storedValueField.Comments.Add(new CodeCommentStatement("Caches the previous register value.", true));

			CodeFieldReferenceExpression storedValueFieldRef = 
				new CodeFieldReferenceExpression(
					new CodeThisReferenceExpression(), 
					"StoredValue"
				);

			initializeMethod.Statements.Add(
				new CodeAssignStatement(
					storedValueFieldRef, 
					new CodeObjectCreateExpression(
						"Integer", 
						new CodePrimitiveExpression(storedValueField.Width), 
						new CodePrimitiveExpression(storedValueField.Signed ? true : false)
					)
				)
			);
			//initializeMethod.Comments.Add(new CodeCommentStatement("Caches the register value."));

			tickMethod = AddMethod("Tick");
			//tickMethod.Comments.Add(new CodeCommentStatement("Updates the register value at the end of each simulation cycle"));

			
			CodeFieldReferenceExpression valueFieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Value");
			tickMethod.Statements.Add(new CodeMethodInvokeExpression(storedValueFieldRef, "ValueCopy", valueFieldRef));
    }
  }
}
